<template>
  <div>
    <el-form ref="inspectionEditForm" :model="formItem" label-width="120px" size="mini">
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="服务编号" prop="registerCode">
            <el-input v-model="registerCode" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="巡检厅局" prop="unitName">
            <el-input v-model="unitName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="执行人" prop="executorName">
            <el-input v-model="formItem.executorName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="formItem.startTime"
              disabled
              type="date"
              placeholder="选择开始时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="formItem.endTime"
              disabled
              type="date"
              placeholder="选择结束时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="存在问题" prop="problems">
            <el-input
              v-model="formItem.problems"
              placeholder="请填写存在问题"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 3 }"
              resize="none"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="解决情况" prop="solveSituation">
            <el-input
              v-model="formItem.solveSituation"
              placeholder="请填写解决情况"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 3 }"
              resize="none"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <div class="form-info-title">
            <span>重保巡检</span>
          </div>
        </el-col>
        <el-col :span="24">
          <PageableTable ref="table" :loading="false" :table-height="400" :data="formItem.inspectionTaskItem" :span-method="objectSpanMethod" :disable-pageable="true">
            <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
              <template slot-scope="scope">
                <column-render :render="column.render" :row="scope.row" :column="column" />
              </template>
            </el-table-column>
          </PageableTable>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { inspectionUpdate, inspectionSubmit, inspectionDetail } from '@neu/dcom-ui/api/insuranceRegisterTask'
import PageableTable from '@neu/biz-core/components/PageableTable'
import { findByDictionaryType } from '@neu/dcom-ui/api/dictionary'
import { clone } from '@neu/biz-core/utils/utils'
// 定义一个表单原始项
const formItem = {
  code: '',
  startTime: '',
  endTime: '',
  cronExp: '',
  executorCode: '',
  executorName: '',
  unitCode: '',
  problems: '',
  solveSituation: '',
  status: '',
  type: '',
  inspectionTaskItem: []
}
export default {
  name: 'InspectionEditForm',
  components: {
    PageableTable
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    },
    registerCode: {
      required: false,
      type: String,
      default: ''
    },
    unitName: {
      required: false,
      type: String,
      default: ''
    },
    inspectionStatus: {
      required: false,
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 编辑的表单内容
      formItem: clone(formItem),
      insideColumns: [
        { title: '类别', key: 'item.itemType', display: true, render: (h, params) => {
          const status = this.types.filter(t => {
            return t.code === params.row.item.itemType
          })
          const statusDesc = status.length === 1 ? status[0].text : params.row.statusDesc
          return h('span', statusDesc)
        } },
        { title: '内容', key: 'item.item', display: true, render: (h, params) => {
          return h('span', params.row.item.item)
        } },
        { title: '结果值', key: 'value', display: true,
          render: (h, params) => {
            if (params.row.item.dataType === 'select') {
              return (
                <div>
                  <el-radio-group v-model={params.row.value}>
                    <el-radio label={'正常'}>正常</el-radio>
                    <el-radio label={'异常'}>异常</el-radio>
                  </el-radio-group>
                </div>
              )
            } else {
              return (
                <div>
                  <el-input v-model={params.row.value}/>
                </div>
              )
            }
          }
        },
        { title: '异常判断规则', key: 'item.rule', display: true,
          render: (h, params) => {
            return h('span', params.row.item.rule)
          }
        },
        { title: '异常原因', key: 'reason', display: true,
          render: (h, params) => {
            return (
              <div>
                <el-input v-model={params.row.reason}/>
              </div>
            )
          }
        }
      ],
      types: [],
      itemTypeArr: [],
      itemTypePos: 0

    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler() {
        if (this.id) {
          this.fetch()
        }
      },
      immediate: true
    }
  },
  created() {
    findByDictionaryType('hnInspectionItemType').then(res => {
      if (res.status === 'success') {
        this.types = res.data
      }
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        inspectionDetail(this.id, this.inspectionStatus).then(response => {
          console.log(response.data)
          this.formItem = {
            ...response.data
          }
          this.formItem.executorName = this.$store.state.user.name
          this.formItem.inspectionTaskItem = this.formItem.inspectionTaskItem.sort((v1, v2) => {
            const x = v1.item.itemType.toLowerCase()
            const y = v2.item.itemType.toLowerCase()
            if (x < y) { return -1 }
            if (x > y) { return 1 }
            return 0
          })
          this.formItem.inspectionTaskItem = this.formItem.inspectionTaskItem.sort((v1, v2) => {
            if (v1.item.itemType === v2.item.itemType) {
              return v1.item.sort - v2.item.sort
            }
            return 0
          })
          this.merge()
        })
      } else {
        this.formItem = clone(formItem)
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      console.log('保存')
      console.log(this.formItem)
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.inspectionEditForm.validate((valid) => {
          if (valid) {
            if (updated) {
              resolve(inspectionUpdate(this.id, this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    // 提交操作，返回promise，后续处理交由调用者处理
    submit() {
      console.log('提交')
      console.log(this.formItem)
      return new Promise(resolve => {
        this.$refs.inspectionEditForm.validate((valid) => {
          if (valid) {
            resolve(inspectionSubmit(this.id, this.formItem))
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.inspectionEditForm.resetFields()
    },
    merageInit() {
      this.itemTypeArr = []
      this.itemTypePos = 0
    },
    merge() {
      this.merageInit()
      for (let i = 0; i < this.formItem.inspectionTaskItem.length; i++) {
        if (i === 0) {
          // 第一行必须存在
          this.itemTypeArr.push(1)
          this.itemTypePos = 0
        } else {
          // 判断当前元素与上一个元素是否相同,eg：this.itemTypePos 是 this.itemTypeArr
          // 第一列
          if (this.formItem.inspectionTaskItem[i].item.itemType === this.formItem.inspectionTaskItem[i - 1].item.itemType) {
            this.itemTypeArr[this.itemTypePos] += 1
            this.itemTypeArr.push(0)
          } else {
            this.itemTypeArr.push(1)
            this.itemTypePos = i
          }
        }
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
      // 第一列的合并方法
        const row1 = this.itemTypeArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0 // 如果被合并了row = 0; 则他这个列需要取消
        return {
          rowspan: row1,
          colspan: col1
        }
      }
    }
  }
}
</script>

